<script setup lang="ts">
import address from '~/data/address';
import { providers, FixedNumber } from 'ethers'
import { depositHistory } from '~/api'
import moment from 'moment'

const router = useRouter()
const lastTxn = ref(localStorage.getItem('lastTxn') || '')

const go = (path: string) => {
  router.push(path)
}

const ALL_NETWORKS_NAME = Object.keys(address)
const balances = ref([] as number[])
const balancesGot = ref(false)

const chain = ref(ALL_NETWORKS_NAME[0])

const next = () => {
  localStorage.setItem('chain', chain.value)
  go('mnemonic')
}

const RPC_URL = 'https://goerli.infura.io/v3/8b55e04e99464356a003d3b7032504aa'
const provider = new providers.JsonRpcProvider(RPC_URL)

const history = ref(null as any)
const historyLoaded = ref(false)

const short = (addr: string) => {
  return `${addr.slice(0, 6)}...${addr.slice(addr.length - 4, addr.length)}`
}

watch(chain, async () => {
  console.log(`chain is ${chain.value}`);
  const contractAddr = (address as any)[chain.value]

  historyLoaded.value = false
  history.value = await depositHistory(contractAddr)
  historyLoaded.value = true
  console.log(history.value);
}, {
  immediate: true
})

onMounted(async () => {
  const balancePromises = Object.values(address).map((addr => provider.getBalance(addr)))
  const balancesBn = await Promise.all(balancePromises)
  balances.value = balancesBn.map(item => FixedNumber.from(item).divUnsafe(FixedNumber.from('1000000000000000000')).toUnsafeFloat())
  balancesGot.value = true
})

const goTx = (tx: string) => {
  window.location.href = 'https://goerli.etherscan.io/tx/' + tx
}

const trueTime = (utcTime: string) => {
  const date = new Date(`${utcTime} UTC`)
  // 2022-03-14 09:36:20
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

</script>

<template>
  <div class="home">
    <div class="card">
      <div class="title">Choose Chain</div>
      <div class="mb-2">Choose which chain you would like to deposit:</div>
      <div class="line mb-1" v-for="(item, index) in ALL_NETWORKS_NAME">
        <input
          name="chain"
          :value="item"
          type="radio"
          v-model="chain"
          :checked="item == ALL_NETWORKS_NAME[0]"
        />
        <div class="ml-1 mr-1">{{ item }}</div>
        <div v-if="balancesGot" style="color: green">({{ balances[index].toFixed(2) }} ETH)</div>
      </div>

      <div v-if="!balancesGot">(Beacon Contract Balance: Loading...)</div>
      <div v-else style="color: green">Beacon Contract Balance is shown above.</div>
      <!-- <div class="line">
        <input name="chain" type="radio">
        <div class="ml-1">I have already down load my keystore.</div>
      </div>-->
      <div class="btn-in-card mt-5" @click="next" v-show="!lastTxn">Next</div>
    </div>
    <div class="card p-0" style="padding">
      <div class="sub p-4">Latest Deposit on {{ chain }}</div>
      <div v-if="!historyLoaded" class="p-3">Loading...</div>
      <div v-else>
        <table class="history-table">
          <thead>
            <tr>
              <!-- <th>#</th> -->
              <th>Time</th>
              <th>Address</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item) in history" @click="goTx(item.transaction.hash)">
              <!-- <td>{{ item.block.height }}</td> -->
              <td>{{ trueTime(item.block.timestamp.time) }}</td>
              <td>{{ short(item.address.address) }}</td>
            </tr>
          </tbody>
        </table>
        <a :href="'https://goerli.etherscan.io/address/' + (address as any)[chain]">
          <div class="btn-in-card m-4">View More</div>
        </a>
      </div>
    </div>
  </div>
</template>

<style scoped>
.home {
  padding: 15px;
}

.list {
  margin-left: 15px;
}

.history-table {
  width: 100%;
}

.history-table tr:not(:last-child) td,
.history-table th {
  border-bottom: 1px solid #00000033;
}

.history-table tr td,
.history-table th {
  padding: 0.5rem 15px;
}

tr > :nth-child(1) {
  text-align: left;
}

tr > :nth-child(2) {
  text-align: right;
}
</style>
